package com.svse.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: liyuhang
 * @Date: 2019-08-27 11:27
 * @Description: excel导出工具类
 */

public class EasyExcelUtil {

    private static Logger log = LoggerFactory.getLogger(EasyExcelUtil.class);
    /**
     * @param response response
     * @param data     数据
     * @param titles   表格列名
     * @param filename 文件名
     */
    public static void exportExcelByMap(HttpServletResponse response, List<Map<String, Object>> data, List<List<String>> titles, String filename) {

        try {
            ServletOutputStream out = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            String fileName = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            // 动态添加表头，适用一些表头动态变化的场景
            Sheet sheet = new Sheet(1, 0);
            sheet.setSheetName("sheet1");
            Table table = new Table(1);
            // 无注解的模式，动态添加表头
            table.setHead(titles);
            writer.write1(createDate(data, titles), sheet, table);
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            out.flush();
            writer.finish();
            out.close();

        } catch (Exception e) {
            log.error("EasyExcelUtil.exportExcelByMap: " + e.getMessage(), e);
        }

    }

    private static List<List<String>> createTitles(List<Map<String, String>> titles) {
        List<List<String>> head = new ArrayList<>();

        for (Map<String, String> map : titles) {
            map.forEach((key, val) -> {
                List<String> headCoulumn = new ArrayList<>();
                headCoulumn.add(val);
                head.add(headCoulumn);
            });
        }
        return head;
    }

    private static List<List<Object>> createDate(List<Map<String, Object>> data, List<List<String>> titles) {

        List<String> column = new ArrayList<>();
        List<Object> eachRow = new ArrayList<>();
        List<List<Object>> result = new ArrayList<>();

        for (List<String> list : titles) {
            list.forEach(key -> {
                column.add(key);
            });
        }

        for (Map<String, Object> dataMap : data) {
            for (String key : column) {
                dataMap.forEach((key1, val1) -> {
                    if (key.equals(key1)) {
                        eachRow.add(val1);
                    }
                });
            }
            result.add(eachRow);
        }

        return result;
    }

    public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class clazz) throws Exception {
        //表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置内容靠左对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        EasyExcel.write(getOutputStream(fileName, response), clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .doWrite(data);
    }
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        return response.getOutputStream();
    }



}

